from django import forms
from django.shortcuts import render, redirect

from StuApp.models import UserInfo, StudentInfo, ClassInfo, GradeInfo


# 主界面函数
def index(request):
    """
    首页视图函数
    功能：
        1. 检查用户是否已登录
        2. 如果未登录则重定向到登录页面
        3. 如果已登录则渲染首页
    参数：
        request: HTTP请求对象
    返回：
        重定向到登录页面或渲染后的首页
    """
    # 检查session中是否存在user_id，判断用户是否已登录
    if not request.session.get('user_id'):
        # 如果未登录，重定向到登录页面，并传递next参数以便登录后跳转回首页
        return redirect(f'login?next={request.path}')

    # 统计数据
    class_count = ClassInfo.objects.count()  # 班级数
    student_count = StudentInfo.objects.count()  # 学生数
    grade_count = GradeInfo.objects.count()  # 年级数
    profession_count = len(StudentInfo.profession_choices)  # 专业数

    # 性别比例
    male_count = StudentInfo.objects.filter(student_gender='1').count()  # 男生数
    female_count = StudentInfo.objects.filter(student_gender='2').count()  # 女生数

    # 专业分布
    profession_data = []
    for code, name in StudentInfo.profession_choices:
        count = StudentInfo.objects.filter(student_profession=code).count()  # 专业分布
        profession_data.append({'name': name, 'count': count})

    context = {
        'class_count': class_count,  # 班级数
        'student_count': student_count,  # 学生数
        'grade_count': grade_count,  # 年级数
        'profession_count': profession_count,  # 专业数
        'male_count': male_count,  # 男生数
        'female_count': female_count,  # 女生数
        'profession_data': profession_data,  # 专业分布
    }
    return render(request, "index.html", context)


# 注销函数
def logout(request):
    """
    用户注销
    :param request:
    :return:
    """
    request.session.flush()  # 清除会话数据
    return redirect('login')  # 重定向到登录页面


# 登录表单
class LoginForm(forms.Form):
    """
    使用form创建登录表单类
    """
    username = forms.CharField(min_length=3, widget=forms.TextInput(attrs={'placeholder': "账号"}))
    password = forms.CharField(min_length=6, widget=forms.PasswordInput(attrs={'placeholder': "密码"}))


# 注册表单


class RegisterForm(forms.ModelForm):
    """
    使用form创建注册表单类
    """
    username = forms.CharField(min_length=3, widget=forms.TextInput(attrs={'placeholder': "账号"}))
    password = forms.CharField(min_length=6, widget=forms.PasswordInput(attrs={'placeholder': "密码"}))
    password2 = forms.CharField(min_length=6, widget=forms.PasswordInput(attrs={'placeholder': "确认密码"}))

    class Meta:
        model = UserInfo
        fields = ['username', 'password', 'password2']


# 用户登录注册界面
def stuLogin(request):
    """
    学生登录视图函数
    处理登录和注册请求，通过前端隐藏字段区分操作类型
    :param request: HTTP请求对象
    :return: 渲染后的登录页面或重定向到首页
    """

    # get请求返回网页
    # 处理GET请求，返回登录页面
    if request.method == 'GET':
        login_form = LoginForm()
        register_form = RegisterForm()
        # 关键修改：初始显示登录界面，设置 is_signup=False
        return render(request, "login.html", {
            "login_form": login_form,
            "register_form": register_form,
            "is_signup": False  # 初始显示登录界面
        })

    # 获取表单类型（登录或注册）
    form_type = request.POST.get("form_type")

    # 处理登录请求
    if form_type == "login":
        form = LoginForm(data=request.POST)  # 使用POST数据初始化登录表单
        # hook检验
        if form.is_valid():  # 验证表单数据是否有效
            username = form.cleaned_data['username']  # 获取用户名
            password = form.cleaned_data['password']  # 获取密码

            # 查询数据库中的用户
            user = UserInfo.objects.filter(username=username).first()
            if user and user.password == password:  # 验证用户名和密码
                # 设置session信息
                request.session['user_id'] = user.username  # 使用username作为session的user_id
                request.session['username'] = user.username
                return redirect("index")  # 登录成功，重定向到首页
            elif user:  # 用户名存在但密码错误
                form.add_error("password", "密码错误")
            else:  # 用户名不存在
                form.add_error("username", "不存在该用户")
        # 登录失败，返回登录页面并显示错误信息
        return render(request, "login.html", {
            "login_form": form,
            "register_form": RegisterForm(),
            "is_signup": False  # 确保停留在登录界面
        })

    # 处理注册请求
    elif form_type == "register":
        form = RegisterForm(data=request.POST)  # 使用POST数据初始化注册表单
        if form.is_valid():  # 验证表单数据是否有效
            username = form.cleaned_data['username']  # 获取用户名
            if UserInfo.objects.filter(username=username).exists():  # 检查用户名是否已存在
                form.add_error("username", "用户名已存在")

            elif form.cleaned_data['password'] != form.cleaned_data['password2']:
                form.add_error("password2", "前后密码不一致")

            else:
                form.save()  # 保存新用户
                return redirect("login")  # 注册成功，重定向到登录页面

        # 注册验证失败的处理逻辑
        return render(request, "login.html", {
            "login_form": LoginForm(),
            "register_form": form,
            "is_signup": True  # 确保显示注册界面
        })


class ChangePasswordForm(forms.Form):
    old_password = forms.CharField(label="原密码", min_length=6, widget=forms.PasswordInput(attrs={'placeholder': "原密码", 'class': 'form-control'}))
    new_password1 = forms.CharField(label="新密码", min_length=6, widget=forms.PasswordInput(attrs={'placeholder': "新密码", 'class': 'form-control'}))
    new_password2 = forms.CharField(label="确认新密码", min_length=6, widget=forms.PasswordInput(attrs={'placeholder': "确认新密码", 'class': 'form-control'}))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

    def clean_old_password(self):
        old_password = self.cleaned_data.get('old_password')
        if self.user and self.user.password != old_password:
            raise forms.ValidationError('原密码不正确')
        return old_password

    def clean(self):
        cleaned_data = super().clean()
        new_password1 = cleaned_data.get('new_password1')
        new_password2 = cleaned_data.get('new_password2')
        if new_password1 and new_password2 and new_password1 != new_password2:
            self.add_error('new_password2', '两次输入的新密码不一致')
        return cleaned_data

from django.contrib import messages

def change_password(request):
    user_id = request.session.get('user_id')
    if not user_id:
        return redirect('login')
    user = UserInfo.objects.filter(username=user_id).first()
    if not user:
        return redirect('login')

    if request.method == 'POST':
        form = ChangePasswordForm(request.POST, user=user)
        if form.is_valid():
            user.password = form.cleaned_data['new_password1']
            user.save()
            request.session.flush() # 清空session
            messages.success(request, '密码修改成功！正在跳转到登录页...')
            return render(request, 'change_password.html', {'form': ChangePasswordForm(), 'title': '密码修改'})
    else:
        form = ChangePasswordForm(user=user)
    return render(request, 'change_password.html', {'form': form, 'title': '密码修改'})
